<template>
  <div class="client-config">
    <!-- 配置筛选和管理 -->
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card class="config-filter-card">
          <template #header>
            <div class="card-header">
              <span class="card-title">
                <el-icon><Setting /></el-icon>
                配置管理
              </span>
              <div class="card-actions">
                <el-button type="primary" size="small" @click="showNewConfigDialog">
                  <el-icon><Plus /></el-icon>
                  新增配置
                </el-button>
                <el-button type="info" size="small" @click="refreshClients">
                  <el-icon><Refresh /></el-icon>
                  刷新客户端
                </el-button>
              </div>
            </div>
          </template>

          <div class="filter-section">
            <el-row :gutter="16">
              <el-col :span="6">
                <el-select
                  v-model="configFilter.type"
                  placeholder="配置类型"
                  @change="handleConfigFilterChange"
                  style="width: 100%"
                >
                  <el-option label="全部配置" value="" />
                  <el-option label="全局配置" value="global" />
                  <el-option label="部门配置" value="department" />
                  <el-option label="个人配置" value="individual" />
                </el-select>
              </el-col>
              <el-col :span="6">
                <el-select
                  v-model="configFilter.department"
                  placeholder="选择部门"
                  clearable
                  @change="handleConfigFilterChange"
                  style="width: 100%"
                  :disabled="configFilter.type === 'global'"
                >
                  <el-option label="全部部门" value="" />
                  <el-option
                    v-for="dept in departments"
                    :key="dept.id"
                    :label="dept.name"
                    :value="dept.id"
                  />
                </el-select>
              </el-col>
              <el-col :span="6">
                <el-select
                  v-model="configFilter.client"
                  placeholder="选择客户端"
                  clearable
                  @change="handleConfigFilterChange"
                  style="width: 100%"
                  :disabled="configFilter.type !== 'individual'"
                >
                  <el-option label="全部客户端" value="" />
                  <el-option
                    v-for="client in allClients"
                    :key="client.id"
                    :label="`${client.name} (${client.ip})`"
                    :value="client.id"
                  />
                </el-select>
              </el-col>
              <el-col :span="6">
                <el-button type="primary" @click="handleConfigFilterChange">
                  <el-icon><Search /></el-icon>
                  查询配置
                </el-button>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 配置列表 -->
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card class="config-list-card">
          <template #header>
            <span class="card-title">
              <el-icon><List /></el-icon>
              配置列表
            </span>
          </template>

          <el-table
            :data="filteredConfigs"
            stripe
            style="width: 100%"
            v-loading="loading"
            :empty-text="loading ? '加载中...' : '暂无配置数据'"
          >
            <el-table-column prop="name" label="配置名称" width="200" show-overflow-tooltip>
              <template #default="{ row }">
                {{ row.name || '未命名配置' }}
              </template>
            </el-table-column>
            <el-table-column prop="type" label="配置类型" width="120">
              <template #default="{ row }">
                <el-tag :type="getConfigTypeTagType(row.type)" v-if="row.type">
                  {{ getConfigTypeText(row.type) }}
                </el-tag>
                <span v-else>未知类型</span>
              </template>
            </el-table-column>
            <el-table-column prop="target" label="应用目标" width="200" show-overflow-tooltip>
              <template #default="{ row }">
                {{ getConfigTargetText(row) }}
              </template>
            </el-table-column>
            <el-table-column prop="description" label="描述" show-overflow-tooltip>
              <template #default="{ row }">
                {{ row.description || '无描述' }}
              </template>
            </el-table-column>
            <el-table-column label="配置状态" width="120">
              <template #default="{ row }">
                <el-tag :type="(row.enabled !== false) ? 'success' : 'info'">
                  {{ (row.enabled !== false) ? '已启用' : '已禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="更新时间" width="160">
              <template #default="{ row }">
                {{ formatDateTime(row.updated_at || row.updatedAt) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="320" align="center" fixed="right">
              <template #default="{ row }">
                <div style="display: flex; justify-content: center; gap: 4px;">
                  <el-button
                    type="primary"
                    size="small"
                    @click="editConfig(row)"
                    :loading="loading"
                    :disabled="!row.id"
                    style="margin: 0;"
                  >
                    <el-icon><Edit /></el-icon>
                    <span style="margin-left: 2px;">编辑</span>
                  </el-button>
                  <el-button
                    type="success"
                    size="small"
                    @click="applyConfig(row)"
                    :loading="applying"
                    :disabled="!row.id"
                    style="margin: 0;"
                  >
                    <el-icon><Check /></el-icon>
                    <span style="margin-left: 2px;">应用</span>
                  </el-button>
                  <el-button
                    type="danger"
                    size="small"
                    @click="deleteConfig(row)"
                    :disabled="!row.id || (row.type === 'global' && row.name && row.name.includes('默认'))"
                    style="margin: 0;"
                  >
                    <el-icon><Delete /></el-icon>
                    <span style="margin-left: 2px;">删除</span>
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>

          <el-empty
            v-if="filteredConfigs.length === 0"
            description="暂无配置数据"
            :image-size="100"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 配置编辑 -->
    <el-row :gutter="20" v-if="currentConfig">
      <el-col :span="24">
        <el-card class="config-edit-card">
          <template #header>
            <div class="card-header">
              <span class="card-title">
                <el-icon><Edit /></el-icon>
                {{ isEditMode ? '编辑配置' : '新增配置' }}
              </span>
              <div class="card-actions">
                <el-button type="success" size="small" @click="saveConfig" :loading="saving">
                  <el-icon><Check /></el-icon>
                  保存配置
                </el-button>
                <el-button type="info" size="small" @click="cancelEdit">
                  <el-icon><Close /></el-icon>
                  取消
                </el-button>
              </div>
            </div>
          </template>

          <!-- 配置基本信息 -->
          <div class="config-basic-info">
            <el-row :gutter="16">
              <el-col :span="8">
                <el-form-item label="配置名称" required>
                  <el-input v-model="currentConfig.name" placeholder="请输入配置名称" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="配置类型" required>
                  <el-select v-model="currentConfig.type" placeholder="选择配置类型" @change="handleConfigTypeChange">
                    <el-option label="全局配置" value="global" />
                    <el-option label="部门配置" value="department" />
                    <el-option label="个人配置" value="individual" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="应用目标" v-if="currentConfig && currentConfig.type !== 'global'">
                  <el-select
                    v-model="currentConfig.targetId"
                    :placeholder="currentConfig && currentConfig.type === 'department' ? '选择部门（可选）' : '选择客户端（可选）'"
                    @change="handleClientSelection"
                    clearable
                  >
                    <template v-if="currentConfig && currentConfig.type === 'department'">
                      <el-option
                        v-for="dept in departments"
                        :key="dept.id"
                        :label="dept.name"
                        :value="dept.id"
                      />
                    </template>
                    <template v-else-if="currentConfig">
                      <el-option
                        v-for="client in allClients"
                        :key="client.id"
                        :label="`${client.name} (${client.ip})`"
                        :value="client.id"
                      />
                    </template>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="配置描述">
                  <el-input
                    v-model="currentConfig.description"
                    type="textarea"
                    :rows="2"
                    placeholder="请输入配置描述"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-alert
                  :title="getApplyHint()"
                  type="info"
                  :closable="false"
                  show-icon
                  style="margin-bottom: 16px"
                />
              </el-col>
            </el-row>
          </div>

          <!-- 基础配置信息 -->
          <div v-if="currentConfig.type === 'individual' && selectedClientInfo" class="client-basic-info">
            <el-divider content-position="left">
              <el-icon><User /></el-icon>
              基础配置信息
            </el-divider>

            <el-descriptions :column="3" border>
              <el-descriptions-item label="客户端名称">
                {{ selectedClientInfo.name }}
              </el-descriptions-item>
              <el-descriptions-item label="用户">
                {{ selectedClientInfo.user || '未分配' }}
              </el-descriptions-item>
              <el-descriptions-item label="部门">
                {{ getDepartmentName(selectedClientInfo.departmentId) }}
              </el-descriptions-item>
              <el-descriptions-item label="IP地址">
                {{ selectedClientInfo.ip }}
              </el-descriptions-item>
              <el-descriptions-item label="状态">
                <el-tag :type="selectedClientInfo.status === 'online' ? 'success' : 'danger'">
                  {{ selectedClientInfo.status === 'online' ? '在线' : '离线' }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="最后心跳">
                {{ selectedClientInfo.lastHeartbeat }}
              </el-descriptions-item>
            </el-descriptions>
          </div>

          <el-form
            ref="configFormRef"
            :model="currentConfig.settings"
            label-width="150px"
            v-loading="loading"
          >
            <!-- 网络管控设置 -->
            <el-divider content-position="left">
              <el-icon><Connection /></el-icon>
              网络管控设置
            </el-divider>

            <el-form-item label="USB管控">
              <el-radio-group v-model="currentConfig.settings.usbPolicy">
                <el-radio value="allow">允许</el-radio>
                <el-radio value="block">禁止</el-radio>
                <el-radio value="whitelist">白名单模式</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="USB白名单" v-if="currentConfig.settings.usbPolicy === 'whitelist'">
              <div class="form-help">Windows：示例
                "USBSTOR\\DISK&VEN_KINGSTON&PROD_DATATRAVELER_3.0&REV_PMAP\\E0D55E6B6466E72188300435&0",

                // Linux 示例 "E0D55E6B6466E72188300435&0"。
                注意：每行一个设备，不支持英文逗号分隔</div>

              <el-input
                v-model="currentConfig.settings.usbWhitelist"
                type="textarea"
                :rows="3"
                placeholder="每行一个USB设备ID或设备名称，例如：Windows 示例 USBSTOR\\DISK&VEN_KINGSTON&PROD_DATATRAVELER_3.0&REV_PMAP\\E0D55E6B6466E72188300435&0, Linux 示例 E0D55E6B6466E72188300435 注意：每行一个设备，不支持英文逗号分隔"
              />
            </el-form-item>

            <el-form-item label="WIFI管控">
              <el-radio-group v-model="currentConfig.settings.wifiPolicy">
                <el-radio value="allow">允许</el-radio>
                <el-radio value="block">禁止</el-radio>
                <el-radio value="whitelist">白名单模式</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="WIFI白名单" v-if="currentConfig.settings.wifiPolicy === 'whitelist'">
              <div class="form-help">允许连接的WIFI网络名称列表。示例：Office-WiFi, Home-Network。注意：每行一个网络名称，不支持英文逗号分隔</div>
              <el-input
                v-model="currentConfig.settings.wifiWhitelist"
                type="textarea"
                :rows="3"
                placeholder="每行一个WIFI名称，例如：Office-WiFi, Home-Network"
              />
            </el-form-item>

            <!-- 流量控制设置 -->
            <el-divider content-position="left">
              <el-icon><DataLine /></el-icon>
              流量控制设置
            </el-divider>

            <el-form-item label="启用流量控制">
              <el-switch
                v-model="currentConfig.settings.enableTrafficControl"
                active-text="启用"
                inactive-text="禁用"
              />
            </el-form-item>

            <div v-if="currentConfig.settings.enableTrafficControl">
              <el-form-item label="日流量限制">
                <el-input-number
                  v-model="currentConfig.settings.dailyTrafficLimit"
                  :min="0"
                  :max="10240"
                  controls-position="right"
                  style="width: 200px"
                />
                <span class="unit-text">MB</span>
              </el-form-item>

              <el-form-item label="周流量限制">
                <el-input-number
                  v-model="currentConfig.settings.weeklyTrafficLimit"
                  :min="0"
                  :max="51200"
                  controls-position="right"
                  style="width: 200px"
                />
                <span class="unit-text">MB</span>
              </el-form-item>

              <el-form-item label="月流量限制">
                <el-input-number
                  v-model="currentConfig.settings.monthlyTrafficLimit"
                  :min="0"
                  :max="204800"
                  controls-position="right"
                  style="width: 200px"
                />
                <span class="unit-text">MB</span>
              </el-form-item>
            </div>

            <!-- 域名/IP拦截设置 -->
            <el-divider content-position="left">
              <el-icon><CircleClose /></el-icon>
              域名\网站拦截设置
            </el-divider>

            <el-form-item label="域名、网站黑名单">
              <div class="form-help">禁止访问的网站列表，示例：www.example.com（拦截具体网站）, 注意：每行一个域名，不支持英文逗号分隔</div>
              <el-input
                v-model="currentConfig.settings.domainBlacklist"
                type="textarea"
                :rows="4"
                placeholder="每行一个域名，支持通配符，例如：*.example.com, badsite.com, *.gambling.*"
              />
            </el-form-item>

            <!-- IP黑名单 - 已注释 -->
            <!--
            <el-form-item label="IP黑名单">
              <div class="form-help">禁止访问的IP地址或网段列表。示例：192.168.1.100（单个IP）, 10.0.0.0/8（A类网段）, 172.16.0.0/12（B类网段）。注意：每行一个IP或网段，不支持英文逗号分隔</div>
              <el-input
                v-model="currentConfig.settings.ipBlacklist"
                type="textarea"
                :rows="4"
                placeholder="每行一个IP地址或网段，例如：192.168.1.100, 10.0.0.0/8, 172.16.0.0/12"
              />
            </el-form-item>
            -->

            <!-- 软件黑名单设置 -->
            <el-divider content-position="left">
              <el-icon><Delete /></el-icon>
              软件黑名单设置
            </el-divider>

            <el-form-item label="软件黑名单">
              <div class="form-help">禁止运行的软件名称或路径列表。windows示例：game.exe（具体程序名）linux示例：game 。注意：每行一个软件，不支持英文逗号分隔  </div>
              <el-input
                v-model="currentConfig.settings.softwareBlacklist"
                type="textarea"
                :rows="4"
                placeholder="每行一个软件名称或路径，windows例如：game.exe, C:\Games\*.exe，linux例如： game"
              />
            </el-form-item>

            <!-- 离线预警设置 -->
            <el-divider content-position="left">
              <el-icon><Bell /></el-icon>
              离线预警设置
            </el-divider>

            <el-form-item label="离线超时时间">
              <el-input-number
                v-model="currentConfig.settings.offlineTimeout"
                :min="1"
                :max="60"
                controls-position="right"
                style="width: 200px"
              />
              <span class="unit-text">分钟</span>
            </el-form-item>

            <el-form-item label="预警级别">
              <el-select v-model="currentConfig.settings.alertLevel" style="width: 200px">
                <el-option label="低" value="low" />
                <el-option label="中" value="medium" />
                <el-option label="高" value="high" />
              </el-select>
            </el-form-item>

            <!-- 键鼠设置 -->
            <el-divider content-position="left">
              <el-icon><Mouse /></el-icon>
              键鼠设置
            </el-divider>

            <el-form-item label="启用键鼠监控">
              <div class="form-help"></div>
              <el-switch
                v-model="currentConfig.settings.enableKeyboardMouseMonitor"
                active-text="启用"
                inactive-text="禁用"
              />
            </el-form-item>

            <el-form-item label="操作保存间隔" v-if="currentConfig.settings.enableKeyboardMouseMonitor">
              <div class="form-help"></div>
              <el-input-number
                v-model="currentConfig.settings.keyboardMouseSaveInterval"
                :min="10"
                :max="3600"
                controls-position="right"
                style="width: 200px"
              />
              <span class="unit-text">秒</span>
            </el-form-item>

            <!-- 截图监控设置 -->
            <el-divider content-position="left">
              <el-icon><Camera /></el-icon>
              截图监控设置
            </el-divider>

            <el-form-item label="启用截图监控">
              <div class="form-help"></div>
              <el-switch
                v-model="currentConfig.settings.enableScreenshotMonitor"
                active-text="启用"
                inactive-text="禁用"
              />
            </el-form-item>

            <el-form-item label="截图保存间隔" v-if="currentConfig.settings.enableScreenshotMonitor">
              <div class="form-help"></div>
              <el-input-number
                v-model="currentConfig.settings.screenshotInterval"
                :min="10"
                :max="3600"
                controls-position="right"
                style="width: 200px"
              />
              <span class="unit-text">秒</span>
            </el-form-item>

            <!-- 目录封锁设置 - 已注释 -->
            <!--
            <el-divider content-position="left">
              <el-icon><Files /></el-icon>
              目录封锁设置
            </el-divider>

            <el-form-item label="启用目录封锁">
              <div class="form-help"></div>
              <el-switch
                v-model="currentConfig.settings.enableDirectoryBlocking"
                active-text="启用"
                inactive-text="禁用"
              />
            </el-form-item>

            <div v-if="currentConfig.settings.enableDirectoryBlocking">
              <el-form-item label="VeraCrypt路径">
                <template #default>
                  <div class="form-help">VeraCrypt可执行文件的完整路径，例如：C:\Program Files\VeraCrypt\VeraCrypt.exe</div>
                  <el-input
                    v-model="currentConfig.settings.veracryptPath"
                    placeholder="请输入VeraCrypt可执行文件路径"
                    style="width: 400px"
                  />
                </template>
              </el-form-item>

              <el-form-item label="加密密码">
                <template #default>
                  <div class="form-help">用于VeraCrypt容器加密的密码，请确保密码强度足够</div>
                  <el-input
                    v-model="currentConfig.settings.encryptionPassword"
                    type="password"
                    placeholder="请输入加密密码"
                    style="width: 300px"
                    show-password
                  />
                </template>
              </el-form-item>

              <el-form-item label="封锁目录列表">
                <template #default>
                  <div class="form-help">需要封锁的目录路径列表。每行一个目录路径，例如：C:\SensitiveData, D:\ImportantFiles</div>
                  <el-input
                    v-model="currentConfig.settings.blockedDirectories"
                    type="textarea"
                    :rows="4"
                    placeholder="每行一个目录路径，例如：&#10;C:\SensitiveData&#10;D:\ImportantFiles&#10;E:\ConfidentialDocs"
                  />
                </template>
              </el-form-item>
            </div>
            -->
          </el-form>
        </el-card>
      </el-col>
    </el-row>

    <!-- 应用配置对话框 -->
    <el-dialog
      v-model="applyDialogVisible"
      title="应用配置"
      width="600px"
      :close-on-click-modal="false"
    >
      <div v-if="configToApply">
        <p><strong>配置名称：</strong>{{ configToApply.name }}</p>
        <p><strong>配置描述：</strong>{{ configToApply.description || '无' }}</p>

        <el-divider />

        <el-form label-width="120px">
          <el-form-item label="应用范围" required>
            <el-radio-group v-model="applyScope">
              <el-radio value="individual">指定客户端</el-radio>
              <el-radio value="department">指定部门</el-radio>
              <el-radio value="global">全部客户端</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="选择客户端" v-if="applyScope === 'individual'" required>
            <el-select v-model="applyTargetId" placeholder="请选择客户端" style="width: 100%">
              <el-option
                v-for="client in allClients"
                :key="client.id"
                :label="`${client.name} (${client.ip})`"
                :value="client.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="选择部门" v-if="applyScope === 'department'" required>
            <el-select v-model="applyTargetId" placeholder="请选择部门" style="width: 100%">
              <el-option
                v-for="dept in departments"
                :key="dept.id"
                :label="dept.name"
                :value="dept.id"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="applyDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmApplyConfig" :loading="applying">
            确认应用
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Setting, Plus, Search, List, Edit, Check, Delete, Close,
  Connection, DataLine, CircleClose, Bell, Mouse, User, Refresh, Camera,
  Files
} from '@element-plus/icons-vue'
import { useClientsStore } from '@/stores/clients'
import { configService, departmentsService, clientsService } from '@/services/dataService'
import { useMockData } from '@/config/app.js'

const router = useRouter()
const clientsStore = useClientsStore()

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const applying = ref(false)
const configFormRef = ref()

// 配置筛选
const configFilter = reactive({
  type: '',
  department: '',
  client: ''
})

// 当前编辑的配置
const currentConfig = ref(null)
const isEditMode = ref(false)
const selectedClientInfo = ref(null)

// 应用配置对话框
const applyDialogVisible = ref(false)
const configToApply = ref(null)
const applyScope = ref('individual')
const applyTargetId = ref('')

// 数据存储
const departments = ref([])
const allConfigs = ref([])
const clients = ref([]) // 直接存储客户端数据，不依赖store

// 计算属性
const allClients = computed(() => {
  // 直接返回客户端数组，不依赖store
  return clients.value || []
})

const filteredConfigs = computed(() => {
  let configs = allConfigs.value

  if (configFilter.type) {
    configs = configs.filter(config => config.type === configFilter.type)
  }

  if (configFilter.department && configFilter.type === 'department') {
    configs = configs.filter(config => (config.target_id || config.targetId) === configFilter.department)
  }

  if (configFilter.client && configFilter.type === 'individual') {
    configs = configs.filter(config => (config.target_id || config.targetId) === configFilter.client)
  }

  return configs
})

// 数据加载方法
const loadConfigs = async () => {
  try {
    loading.value = true
    const response = await configService.getConfigs()

    // 处理不同的API响应格式
    if (response) {
      // 检查是否有错误标识
      if (response.success === false || (response.code && response.code !== 200)) {
        console.warn('API返回错误:', response.message || response.error)
        ElMessage.warning(response.message || '获取配置数据失败')
        allConfigs.value = []
        return
      }

      // 处理各种可能的响应格式
      let configList = []

      // 真实API格式: {code: 200, data: {...}, message: 'Success'}
      if (response.code === 200 && response.data) {
        if (Array.isArray(response.data)) {
          // 数据直接是数组: {code: 200, data: [...]}
          configList = response.data
        } else if (response.data.list) {
          // 数据包含list字段: {code: 200, data: {list: [...], total: n}}
          configList = response.data.list
        } else if (response.data.configs) {
          // 数据包含configs字段: {code: 200, data: {configs: [...]}}
          configList = response.data.configs
        } else {
          console.warn('真实API响应格式未识别:', response.data)
          configList = []
        }
      } else if (response.data && response.data.list) {
        // 虚拟数据格式: {success: true, data: {list: [...], total: n}}
        configList = response.data.list
      } else if (response.list) {
        // 虚拟数据格式: {success: true, list: [...], total: n}
        configList = response.list
      } else if (Array.isArray(response.data)) {
        // 直接返回数组格式: {success: true, data: [...]}
        configList = response.data
      } else if (Array.isArray(response)) {
        // 直接返回数组
        configList = response
      } else {
        console.warn('未识别的API响应格式:', response)
        configList = []
      }

      // 确保每个配置项都有必要的字段
      allConfigs.value = configList.map(config => ({
        ...config,
        // 确保字段一致性
        targetId: config.targetId || config.target_id,
        updatedAt: config.updatedAt || config.updated_at,
        // 确保有默认的enabled状态
        enabled: config.enabled !== undefined ? config.enabled : true,
        // 确保有settings对象
        settings: config.settings || {}
      }))



      if (allConfigs.value.length === 0) {
        ElMessage.info('暂无配置数据')
      }
    } else {
      console.warn('API响应为空')
      allConfigs.value = []
      ElMessage.warning('获取配置数据失败，响应为空')
    }
  } catch (error) {
    console.error('加载配置列表失败:', error)
    ElMessage.error('加载配置列表失败: ' + (error.message || '网络错误'))
    allConfigs.value = []
  } finally {
    loading.value = false
  }
}

// 直接加载客户端数据（不依赖store）
const loadClients = async () => {
  try {
    const response = await clientsService.getClients()

    // 兼容两种API响应格式（与ClientManagement.vue保持一致）
    if (response.success || response.code === 200) {
      let clientsData = []

      if (response.data && response.data.list) {
        // 真实API格式: {code: 200, data: {list: [...]}}
        clientsData = response.data.list
      } else if (response.data && Array.isArray(response.data)) {
        // 备用格式: {code: 200, data: [...]}
        clientsData = response.data
      } else if (response.success && response.data) {
        // 虚拟数据格式: {success: true, data: {list: [...]}}
        clientsData = response.data.list || response.data
      }

      clients.value = clientsData || []
      if (clients.value.length > 0) {
        // 客户端数据加载成功
      }
    } else {
      clients.value = []
    }
  } catch (error) {
    console.error('加载客户端列表失败:', error)
    ElMessage.error('加载客户端列表失败: ' + (error.message || '网络错误'))
    clients.value = []
  }
}

const loadDepartments = async () => {
  try {
    const response = await departmentsService.getDepartmentOptions()

    // 处理不同的API响应格式
    if (response && response.success !== false) {
      if (response.data && Array.isArray(response.data)) {
        // 真实API格式: {success: true, data: [...]}
        departments.value = response.data
      } else if (Array.isArray(response)) {
        // 直接返回数组格式
        departments.value = response
      } else {
        departments.value = []
      }
    } else {
      departments.value = []
      console.warn('部门数据加载失败，使用空数组')
    }
  } catch (error) {
    console.error('加载部门列表失败:', error)
    ElMessage.error('加载部门列表失败: ' + (error.message || '网络错误'))
    departments.value = []
  }
}

// 方法
const handleConfigFilterChange = async () => {
  // 筛选逻辑已在计算属性中处理，但我们可以重新加载数据以确保最新

  try {
    loading.value = true
    // 重新加载配置数据，可以传递筛选参数
    const params = {}
    if (configFilter.type) params.type = configFilter.type
    if (configFilter.department) params.department = configFilter.department
    if (configFilter.client) params.client = configFilter.client

    const response = await configService.getConfigs(params)

    // 处理API响应
    if (response && response.success !== false) {
      if (response.data && response.data.list) {
        allConfigs.value = response.data.list
      } else if (response.list) {
        allConfigs.value = response.list
      } else if (Array.isArray(response.data)) {
        allConfigs.value = response.data
      } else if (Array.isArray(response)) {
        allConfigs.value = response
      } else {
        allConfigs.value = []
      }

      // 根据筛选结果显示不同的消息
      if (allConfigs.value.length > 0) {
        ElMessage.success(`查询成功，找到 ${allConfigs.value.length} 条配置`)
      } else {
        ElMessage.info('未找到符合条件的配置')
      }
    } else {
      allConfigs.value = []
      ElMessage.warning('查询失败，请检查筛选条件')
    }
  } catch (error) {
    console.error('查询配置失败:', error)
    ElMessage.error('查询配置失败: ' + (error.message || '网络错误'))
    allConfigs.value = []
  } finally {
    loading.value = false
  }
}

const showNewConfigDialog = () => {
  // 创建新配置时使用更合理的默认值
  currentConfig.value = {
    id: null,
    name: '',
    type: 'individual',
    targetId: '',
    description: '',
    settings: {
      // USB管控设置
      usbPolicy: 'allow',
      usbWhitelist: '',

      // WIFI管控设置
      wifiPolicy: 'allow',
      wifiWhitelist: '',

      // 流量控制设置
      enableTrafficControl: false,
      dailyTrafficLimit: 2048,    // 2GB
      weeklyTrafficLimit: 10240,  // 10GB
      monthlyTrafficLimit: 40960, // 40GB

      // 域名/IP拦截设置
      domainBlacklist: '',
      // ipBlacklist: '', // 已注释 - IP黑名单功能

      // 软件黑名单设置
      softwareBlacklist: '',

      // 离线预警设置
      offlineTimeout: 5,          // 5分钟
      alertLevel: 'medium',

      // 键鼠监控设置
      enableKeyboardMouseMonitor: false,
      keyboardMouseSaveInterval: 300,  // 5分钟

      // 截图监控设置
      enableScreenshotMonitor: false,
      screenshotInterval: 60,  // 1分钟

      // 目录封锁设置 - 已注释
      // enableDirectoryBlocking: false,
      // veracryptPath: '',
      // encryptionPassword: '',
      // blockedDirectories: ''
    }
  }
  isEditMode.value = false
  selectedClientInfo.value = null

  ElMessage.info('请填写新配置的基本信息和详细设置')
}

const editConfig = async (config) => {
  try {

    // 设置加载状态
    loading.value = true

    // 调用 GET /api/v1/configs/{id} API 获取详细配置数据
    const detailResponse = await configService.getConfig(config.id)

    // 处理API响应数据
    let detailConfig = null
    if (detailResponse) {
      // 处理不同的API响应格式
      if (detailResponse.success !== false && detailResponse.code !== 400) {
        if (detailResponse.data) {
          // 真实API格式: {code: 200, data: {...}}
          detailConfig = detailResponse.data
        } else if (detailResponse.success && detailResponse.id) {
          // 虚拟数据格式: {success: true, id: 1, name: '...', ...}
          detailConfig = detailResponse
        } else if (detailResponse.id) {
          // 直接返回配置对象
          detailConfig = detailResponse
        }
      }
    }

    // 如果API调用失败，使用列表中的配置数据作为备选
    if (!detailConfig) {
      console.warn('配置详情API调用失败，使用列表数据作为备选')
      detailConfig = config
      ElMessage.warning('无法获取配置详情，使用基础数据进行编辑')
    } else {
      ElMessage.success('配置详情加载成功')
    }

    // 深拷贝配置数据
    currentConfig.value = JSON.parse(JSON.stringify(detailConfig))

    // 确保使用统一的字段名
    if (detailConfig.target_id !== undefined) {
      currentConfig.value.targetId = detailConfig.target_id
    }

    // 处理真实API可能的数据结构
    let configSettings = {}

    // 检查不同可能的settings字段位置
    if (detailConfig.settings && typeof detailConfig.settings === 'object') {
      configSettings = detailConfig.settings
    } else if (detailConfig.config && typeof detailConfig.config === 'object') {
      configSettings = detailConfig.config
    } else if (detailConfig.configuration && typeof detailConfig.configuration === 'object') {
      configSettings = detailConfig.configuration
    } else {
      // 如果没有settings，尝试从配置对象的根级别提取设置
      configSettings = {
        usbPolicy: detailConfig.usbPolicy || detailConfig.usb_policy,
        usbWhitelist: detailConfig.usbWhitelist || detailConfig.usb_whitelist,
        wifiPolicy: detailConfig.wifiPolicy || detailConfig.wifi_policy,
        wifiWhitelist: detailConfig.wifiWhitelist || detailConfig.wifi_whitelist,
        enableTrafficControl: detailConfig.enableTrafficControl || detailConfig.enable_traffic_control,
        dailyTrafficLimit: detailConfig.dailyTrafficLimit || detailConfig.daily_traffic_limit,
        weeklyTrafficLimit: detailConfig.weeklyTrafficLimit || detailConfig.weekly_traffic_limit,
        monthlyTrafficLimit: detailConfig.monthlyTrafficLimit || detailConfig.monthly_traffic_limit,
        domainBlacklist: detailConfig.domainBlacklist || detailConfig.domain_blacklist,
        // ipBlacklist: detailConfig.ipBlacklist || detailConfig.ip_blacklist, // 已注释 - IP黑名单功能
        softwareBlacklist: detailConfig.softwareBlacklist || detailConfig.software_blacklist,
        offlineTimeout: detailConfig.offlineTimeout || detailConfig.offline_timeout,
        alertLevel: detailConfig.alertLevel || detailConfig.alert_level,
        enableKeyboardMouseMonitor: detailConfig.enableKeyboardMouseMonitor || detailConfig.enable_keyboard_mouse_monitor,
        keyboardMouseSaveInterval: detailConfig.keyboardMouseSaveInterval || detailConfig.keyboard_mouse_save_interval,
        // enableDirectoryBlocking: detailConfig.enableDirectoryBlocking || detailConfig.enable_directory_blocking, // 已注释 - 目录封锁功能
        // veracryptPath: detailConfig.veracryptPath || detailConfig.veracrypt_path, // 已注释 - 目录封锁功能
        // encryptionPassword: detailConfig.encryptionPassword || detailConfig.encryption_password, // 已注释 - 目录封锁功能
        // blockedDirectories: detailConfig.blockedDirectories || detailConfig.blocked_directories // 已注释 - 目录封锁功能
      }
    }

    // 确保settings对象存在并有默认值
    currentConfig.value.settings = {
      // USB管控设置
      usbPolicy: configSettings.usbPolicy || 'allow',
      usbWhitelist: configSettings.usbWhitelist || '',

      // WIFI管控设置
      wifiPolicy: configSettings.wifiPolicy || 'allow',
      wifiWhitelist: configSettings.wifiWhitelist || '',

      // 流量控制设置
      enableTrafficControl: configSettings.enableTrafficControl || false,
      dailyTrafficLimit: configSettings.dailyTrafficLimit || 2048,
      weeklyTrafficLimit: configSettings.weeklyTrafficLimit || 10240,
      monthlyTrafficLimit: configSettings.monthlyTrafficLimit || 40960,

      // 域名/IP拦截设置
      domainBlacklist: configSettings.domainBlacklist || '',
      // ipBlacklist: configSettings.ipBlacklist || '', // 已注释 - IP黑名单功能

      // 软件黑名单设置
      softwareBlacklist: configSettings.softwareBlacklist || '',

      // 离线预警设置
      offlineTimeout: configSettings.offlineTimeout || 5,
      alertLevel: configSettings.alertLevel || 'medium',

      // 键鼠监控设置
      enableKeyboardMouseMonitor: configSettings.enableKeyboardMouseMonitor || false,
      keyboardMouseSaveInterval: configSettings.keyboardMouseSaveInterval || 300,

      // 截图监控设置
      enableScreenshotMonitor: configSettings.enableScreenshotMonitor || false,
      screenshotInterval: configSettings.screenshotInterval || 60,

      // 目录封锁设置 - 已注释
      // enableDirectoryBlocking: configSettings.enableDirectoryBlocking || false,
      // veracryptPath: configSettings.veracryptPath || '',
      // encryptionPassword: configSettings.encryptionPassword || '',
      // blockedDirectories: configSettings.blockedDirectories || ''
    }


    isEditMode.value = true

    // 如果是个人配置，加载客户端信息
    const targetId = detailConfig.target_id || detailConfig.targetId
    if (detailConfig.type === 'individual' && targetId) {
      const client = allClients.value.find(c => c.id === targetId)
      if (client) {
        selectedClientInfo.value = {
          ...client,
          user: client.user || '未分配用户',
          departmentId: client.dept_id || client.departmentId || 1
        }
      } else {
        console.warn('未找到目标客户端:', targetId)
        selectedClientInfo.value = null
      }
    } else {
      selectedClientInfo.value = null
    }

  } catch (error) {
    console.error('编辑配置失败:', error)
    ElMessage.error('编辑配置失败: ' + (error.message || '网络错误'))

    // 发生错误时清空编辑状态
    currentConfig.value = null
    selectedClientInfo.value = null
    isEditMode.value = false
  } finally {
    // 确保加载状态被清除
    loading.value = false
  }
}

const handleConfigTypeChange = (type) => {

  // 重置目标ID和客户端信息
  currentConfig.value.targetId = ''
  selectedClientInfo.value = null

  if (type === 'global') {
    ElMessage.info('全局配置将应用到所有客户端')
  } else if (type === 'department') {
    ElMessage.info('可选择要应用的部门，不选择则只保存配置')
  } else if (type === 'individual') {
    ElMessage.info('可选择要应用的客户端，不选择则只保存配置')
  }
}

const getApplyHint = () => {
  if (!currentConfig.value) return ''

  if (currentConfig.value.type === 'global') {
    return '保存后将自动应用到所有在线客户端'
  } else if (currentConfig.value.type === 'department') {
    if (currentConfig.value.targetId) {
      const dept = departments.value.find(d => d.id === currentConfig.value.targetId)
      return `保存后将自动应用到 ${dept?.name || '选中'} 部门的所有在线客户端`
    } else {
      return '未选择部门，保存后只存储配置不会应用到任何客户端'
    }
  } else if (currentConfig.value.type === 'individual') {
    if (currentConfig.value.targetId) {
      const client = allClients.value.find(c => c.id === currentConfig.value.targetId)
      return `保存后将自动应用到客户端 ${client?.name || '选中客户端'}`
    } else {
      return '未选择客户端，保存后只存储配置不会应用到任何客户端'
    }
  }
  return ''
}

const saveConfig = async () => {

  // 验证必填字段
  if (!currentConfig.value.name || currentConfig.value.name.trim() === '') {
    ElMessage.error('请输入配置名称')
    return
  }

  // 移除强制要求选择应用对象的验证
  // 现在允许只保存配置而不应用

  // 验证配置设置
  if (currentConfig.value.settings) {
    const settings = currentConfig.value.settings

    // 验证流量限制设置
    if (settings.enableTrafficControl) {
      if (!settings.dailyTrafficLimit || settings.dailyTrafficLimit <= 0) {
        ElMessage.error('请设置有效的日流量限制')
        return
      }
      if (!settings.weeklyTrafficLimit || settings.weeklyTrafficLimit <= 0) {
        ElMessage.error('请设置有效的周流量限制')
        return
      }
      if (!settings.monthlyTrafficLimit || settings.monthlyTrafficLimit <= 0) {
        ElMessage.error('请设置有效的月流量限制')
        return
      }
    }

    // 验证离线超时设置
    if (!settings.offlineTimeout || settings.offlineTimeout <= 0) {
      ElMessage.error('请设置有效的离线超时时间')
      return
    }

    // 验证键鼠监控设置
    if (settings.enableKeyboardMouseMonitor && (!settings.keyboardMouseSaveInterval || settings.keyboardMouseSaveInterval < 10)) {
      ElMessage.error('键鼠操作保存间隔不能少于10秒')
      return
    }

    // 验证截图监控设置
    if (settings.enableScreenshotMonitor && (!settings.screenshotInterval || settings.screenshotInterval < 10)) {
      ElMessage.error('截图保存间隔不能少于10秒')
      return
    }
  }

  saving.value = true

  try {
    // 准备保存的数据
    const saveData = {
      ...currentConfig.value,
      // 确保字段名一致性
      target_id: currentConfig.value.targetId || 0,
      updated_at: new Date().toISOString(),
      // 确保settings对象完整
      settings: {
        ...currentConfig.value.settings
      }
    }


    let response
    if (isEditMode.value) {
      // 更新配置
      response = await configService.updateConfig(currentConfig.value.id, saveData)
      ElMessage.success('配置更新成功')
    } else {
      // 新增配置
      response = await configService.createConfig(saveData)
      ElMessage.success('配置创建成功')
    }

    // 可选应用配置到指定目标
    if (response && (response.id || currentConfig.value.id)) {
      const configId = response.id || currentConfig.value.id

      // 检查是否需要应用配置
      const shouldApply = currentConfig.value.type === 'global' ||
                         (currentConfig.value.type !== 'global' && currentConfig.value.targetId)

      if (shouldApply) {
        try {
          // 构建应用配置的数据
          const applyData = {
            scope: currentConfig.value.type,
            target_id: currentConfig.value.targetId || 0,
            config_id: configId,
            applied_at: new Date().toISOString()
          }

          // 根据配置类型设置应用数据
          if (currentConfig.value.type === 'individual' && currentConfig.value.targetId) {
            applyData.client_ids = [currentConfig.value.targetId]
          } else if (currentConfig.value.type === 'department' && currentConfig.value.targetId) {
            applyData.department_id = currentConfig.value.targetId
          }

          // 调用API应用配置
          const applyResponse = await configService.applyConfig(configId, applyData)

          // 显示应用结果
          let targetText = ''
          if (currentConfig.value.type === 'global') {
            targetText = '全部客户端'
          } else if (currentConfig.value.type === 'department') {
            const dept = departments.value.find(d => d.id === currentConfig.value.targetId)
            targetText = `${dept?.name || '未知'}部门`
          } else {
            const client = allClients.value.find(c => c.id === currentConfig.value.targetId)
            targetText = `客户端 ${client?.name || '未知'}`
          }

          if (applyResponse.failed && applyResponse.failed > 0) {
            ElMessage.warning(`配置已保存并应用到${targetText}，成功${applyResponse.applied || 0}个，失败${applyResponse.failed}个`)
          } else {
            ElMessage.success(`配置已保存并成功应用到${targetText}`)
          }
        } catch (applyError) {
          console.error('应用配置失败:', applyError)
          ElMessage.warning('配置保存成功，但应用失败: ' + (applyError.message || '网络错误'))
        }
      } else {
        // 只保存配置，不应用
        ElMessage.success('配置已保存（未应用到任何客户端）')
      }
    }

    // 重新加载配置列表
    await loadConfigs()

    // 清空当前编辑状态
    currentConfig.value = null
    selectedClientInfo.value = null
    isEditMode.value = false

  } catch (error) {
    console.error('保存配置失败:', error)
    ElMessage.error('保存配置失败: ' + (error.message || '网络错误'))
  } finally {
    saving.value = false
  }
}

const cancelEdit = () => {

  // 清空所有编辑状态
  currentConfig.value = null
  selectedClientInfo.value = null
  isEditMode.value = false

  ElMessage.info('已取消编辑')
}

const applyConfig = (config) => {

  configToApply.value = config
  applyScope.value = 'individual'
  applyTargetId.value = ''
  applyDialogVisible.value = true

  ElMessage.info('请选择配置应用范围')
}

const confirmApplyConfig = async () => {

  if (applyScope.value !== 'global' && !applyTargetId.value) {
    const targetType = applyScope.value === 'department' ? '部门' : '客户端'
    ElMessage.error(`请选择应用${targetType}`)
    return
  }

  applying.value = true

  try {
    // 构建应用配置的数据
    const applyData = {
      scope: applyScope.value,
      target_id: applyTargetId.value || null,
      config_id: configToApply.value.id,
      applied_at: new Date().toISOString()
    }

    // 如果是指定客户端，添加客户端ID列表
    if (applyScope.value === 'individual') {
      applyData.client_ids = [applyTargetId.value]
      // 获取客户端信息用于验证
      const client = allClients.value.find(c => c.id === applyTargetId.value)
      if (!client) {
        ElMessage.error('选择的客户端不存在')
        return
      }
      applyData.client_info = {
        id: client.id,
        name: client.name,
        ip: client.ip,
        status: client.status
      }
    } else if (applyScope.value === 'department') {
      applyData.department_id = applyTargetId.value
      // 获取部门信息用于验证
      const dept = departments.value.find(d => d.id === applyTargetId.value)
      if (!dept) {
        ElMessage.error('选择的部门不存在')
        return
      }
      applyData.department_info = {
        id: dept.id,
        name: dept.name
      }
    }


    // 调用API应用配置
    const response = await configService.applyConfig(configToApply.value.id, applyData)

    // 构建成功消息
    let targetText = ''
    let appliedCount = 0

    if (applyScope.value === 'global') {
      targetText = '全部客户端'
      appliedCount = response.applied || allClients.value.length
    } else if (applyScope.value === 'department') {
      const dept = departments.value.find(d => d.id === applyTargetId.value)
      targetText = `${dept?.name || '未知'}部门`
      appliedCount = response.applied || 1
    } else {
      const client = allClients.value.find(c => c.id === applyTargetId.value)
      targetText = `客户端 ${client?.name || '未知'} (${client?.ip || ''})`
      appliedCount = response.applied || 1
    }

    // 显示详细的成功消息
    if (response.failed && response.failed > 0) {
      ElMessage.warning(`配置"${configToApply.value.name}"已应用到${targetText}，成功${appliedCount}个，失败${response.failed}个`)
    } else {
      ElMessage.success(`配置"${configToApply.value.name}"已成功应用到${targetText}（${appliedCount}个目标）`)
    }

    applyDialogVisible.value = false

    // 重置应用对话框状态
    configToApply.value = null
    applyScope.value = 'individual'
    applyTargetId.value = ''
  } catch (error) {
    console.error('应用配置失败:', error)
    ElMessage.error('应用配置失败: ' + (error.message || '网络错误'))
  } finally {
    applying.value = false
  }
}

const deleteConfig = async (config) => {

  // 检查是否为系统关键配置
  if (config.type === 'global' && config.name.includes('默认')) {
    ElMessage.warning('系统默认配置不能删除')
    return
  }

  try {
    // 构建详细的确认消息
    let confirmMessage = `确定要删除配置"${config.name}"吗？`

    if (config.type === 'global') {
      confirmMessage += '\n\n⚠️ 这是全局配置，删除后将影响所有客户端！'
    } else if (config.type === 'department') {
      const dept = departments.value.find(d => d.id === (config.target_id || config.targetId))
      confirmMessage += `\n\n这将删除${dept?.name || '未知部门'}的部门配置。`
    } else {
      const client = allClients.value.find(c => c.id === (config.target_id || config.targetId))
      confirmMessage += `\n\n这将删除客户端"${client?.name || '未知客户端'}"的个人配置。`
    }

    confirmMessage += '\n\n此操作不可撤销，请谨慎操作！'

    await ElMessageBox.confirm(
      confirmMessage,
      '确认删除配置',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: false,
        distinguishCancelAndClose: true
      }
    )


    // 调用API删除配置
    const response = await configService.deleteConfig(config.id)

    // 重新加载配置列表
    await loadConfigs()

    // 如果当前正在编辑被删除的配置，清空编辑状态
    if (currentConfig.value && currentConfig.value.id === config.id) {
      currentConfig.value = null
      selectedClientInfo.value = null
      isEditMode.value = false
    }

    ElMessage.success(`配置"${config.name}"删除成功`)
  } catch (error) {
    if (error !== 'cancel' && error !== 'close') {
      console.error('删除配置失败:', error)
      ElMessage.error('删除配置失败: ' + (error.message || '网络错误'))
    }
  }
}

// 辅助方法
const getConfigTypeText = (type) => {
  const typeMap = {
    global: '全局配置',
    department: '部门配置',
    individual: '个人配置'
  }
  return typeMap[type] || type
}

const getConfigTypeTagType = (type) => {
  if (!type) return 'info'

  const typeMap = {
    global: 'danger',
    department: 'warning',
    individual: 'success'
  }
  return typeMap[type] || 'info'
}

const getConfigTargetText = (config) => {
  if (!config || !config.type) {
    return '未知目标'
  }

  if (config.type === 'global') {
    return '全部客户端'
  } else if (config.type === 'department') {
    const targetId = config.target_id || config.targetId
    if (!targetId) return '未指定部门'

    const dept = departments.value?.find(d => d.id === targetId)
    return dept ? dept.name : `部门ID: ${targetId}`
  } else if (config.type === 'individual') {
    const targetId = config.target_id || config.targetId
    if (!targetId) return '未指定客户端'

    const client = allClients.value?.find(c => c.id === targetId)
    return client ? `${client.name} (${client.ip})` : `客户端ID: ${targetId}`
  } else {
    return '未知类型'
  }
}

const getDepartmentName = (departmentId) => {
  const dept = departments.value.find(d => d.id === departmentId)
  return dept ? dept.name : '未分配'
}

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '未知'

  try {
    const date = new Date(dateTimeStr)
    if (isNaN(date.getTime())) return dateTimeStr

    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  } catch (error) {
    console.warn('日期格式化失败:', error)
    return dateTimeStr
  }
}

// 监听客户端选择变化
const handleClientSelection = (clientId) => {
  if (currentConfig.value && currentConfig.value.type === 'individual' && clientId) {
    const client = allClients.value.find(c => c.id === clientId)
    if (client) {
      selectedClientInfo.value = {
        ...client,
        user: client.user || '未分配用户',
        departmentId: client.dept_id || client.departmentId || 1
      }
    }
  }
}

// 手动刷新客户端数据
const refreshClients = async () => {
  try {
    await loadClients()
    if (allClients.value.length > 0) {
      ElMessage.success(`客户端数据刷新成功，共 ${allClients.value.length} 个客户端`)
    } else {
      ElMessage.warning('客户端数据为空，请检查API连接')
    }
  } catch (error) {
    console.error('刷新客户端数据失败:', error)
    ElMessage.error('刷新客户端数据失败')
  }
}

// 生命周期
onMounted(async () => {
  try {
    await Promise.all([
      loadClients(),  // 直接加载客户端数据，不依赖store
      loadConfigs(),
      loadDepartments()
    ])
  } catch (error) {
    console.error('数据加载失败:', error)
    ElMessage.error('数据加载失败，请刷新页面重试')
  }
})
</script>

<style scoped>
.client-config {
  max-width: 1400px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
}

.card-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #303133;
}

.card-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.filter-section {
  margin-bottom: 0;
}

.config-filter-card,
.config-list-card,
.config-edit-card {
  margin-bottom: 20px;
}

.config-basic-info {
  margin-bottom: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
}

.client-basic-info {
  margin-bottom: 20px;
}

.form-help {
  font-size: 12px;
  color: #909399;
  margin-bottom: 8px;
  line-height: 1.4;
  display: block;
  width: 100%;
}

.unit-text {
  margin-left: 8px;
  color: #909399;
  font-size: 14px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

.el-table {
  font-size: 14px;
}

.el-descriptions {
  font-size: 14px;
}

@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .card-actions {
    width: 100%;
    justify-content: flex-start;
  }

  .filter-section .el-col {
    margin-bottom: 12px;
  }
}
</style>
